import useCommonUtils from '@/utils/common'
const { formatDate } = useCommonUtils();

const storagePrefix = 'comment-'
class Result {
  constructor(message, data = {}) {
    this.message = message
    this.data = data
  }
}

const getStorageItemById = id => {
  const res = uni.getStorageInfoSync();
  const filterList = res.keys.filter(key => key === `${storagePrefix}${id}`);
  return filterList[0] ? uni.getStorageSync(filterList[0]) : {}
}

const api = {
  add: (data) => {
    data.id = new Date().getTime();
    data.createTime = formatDate(new Date(), 'dateTime')
    return new Promise((resolve) => {
      uni.setStorageSync(`${storagePrefix}${data.id}`, data);
      resolve(new Result('添加成功'))
    })
  },
  delete: id => {
    return new Promise((resolve) => {
      uni.removeStorageSync(`${storagePrefix}${id}`)
      resolve(new Result('删除成功'))
    })
  },
  update: (data) => {
    if (!data.id) {
      console.error('地点update接口参数缺失id')
      return;
    }
    return new Promise((resolve) => {
      const item = getStorageItemById(data.id);
      uni.setStorageSync(`${storagePrefix}${data.id}`, Object.assign({}, item, data));
      resolve(new Result('修改成功'))
    })
  },
  detail: id => {
    return new Promise((resolve) => {
      const item = getStorageItemById(id);
      resolve(new Result('查询成功', item))
    })
  },
  getList: checkStationId => {
    return new Promise((resolve) => {
      const res = uni.getStorageInfoSync();
      const commentList = res.keys.filter(key => key.includes(storagePrefix)).map(key => uni.getStorageSync(key));
      const paginatedList = commentList.filter(item => item.checkStationId === checkStationId);
      resolve(new Result('查询成功', paginatedList))
    })
  },
  getCount: () => {
    return new Promise((resolve) => {
      const res = uni.getStorageInfoSync();
      const keyList = res.keys.filter(key => key.includes(storagePrefix));
      resolve(new Result('查询成功', { totalCount: keyList.length }));
    })
  },
  getRecommendKeyWords: () => {
    return new Promise((resolve) => {
      resolve(new Result('查询成功', [
        { keyword: '高效快捷', isAdd: false },
        { keyword: '环境整洁', isAdd: false },
        { keyword: '设备先进', isAdd: false },
        { keyword: '专业检测', isAdd: false },
        { keyword: '透明流程', isAdd: false },
        { keyword: '价格合理', isAdd: false },
        { keyword: '预约方便', isAdd: false },
        { keyword: '服务态度佳', isAdd: false },
        { keyword: '一站式服务', isAdd: false },
        { keyword: '客户满意度高', isAdd: false }
      ]))
    })
  }
}

export default api
